const express = require('express');
const logger = require('./middleware/logger');
const imagesRouter = require('./routes/images');
const cors = require('cors');
const path = require('path');
const fs = require('fs');

const app = express();

// CORS配置
app.use(cors());

// 中间件配置
app.use(express.json());
app.use(logger);

// 提供静态文件访问
app.use('/uploads', express.static(path.join(__dirname, 'uploads'), {
  setHeaders: (res, path) => {
    res.set('Access-Control-Allow-Origin', '*');
  },
  index: false
}));

// 确保uploads文件夹存在并设置权限
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
  fs.mkdirSync(uploadsDir, { mode: 0o777 });
} else {
  fs.chmodSync(uploadsDir, 0o777);
}

// 路由配置
app.use('/api/images', imagesRouter);

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    code: 500,
    message: '服务器内部错误',
    error: err.message
  });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
}); 